<template>
  <h-page-header title="" :routes="routes"> </h-page-header>
  <main class="user-main">
    <a-row>
      <section class="table-body">
        <a-col :span="24">
          <section class="form-main">
            <a-form layout="inline" :model="formState">
              <a-form-item label="用户名">
                <a-input
                  v-model:value="formState.username"
                  placeholder="请输入用户名"
                />
              </a-form-item>
              <a-form-item label="手机号">
                <a-input
                  v-model:value="formState.phone"
                  placeholder="请输入手机号"
                />
              </a-form-item>
              <a-form-item style="position: absolute; right: 0px">
                <a-button type="primary" @click="handleSearch(formState)"
                  >查询</a-button
                >
                <a-button
                  type="default"
                  style="margin-left: 20px"
                  @click="handleReset"
                  >重置</a-button
                >
              </a-form-item>
            </a-form>
            <a-button
              style="margin: 20px 20px 0 0"
              @click="handleAdd(formState)"
              type="primary"
              >添加</a-button
            >
            <a-button
              style="margin-top: 20px"
              @click="handleDelete(formState)"
              type="primary"
              danger
              >删除</a-button
            >
          </section>
          <a-divider />
          <a-table
            :columns="columns"
            :data-source="dataSource.list"
            bordered
            :pagination="pagination"
            :row-selection="rowSelection"
          >
            <template #bodyCell="{ column, text, record }">
              <template
                v-if="
                  ['username', 'password', 'phone', 'email', 'status'].includes(
                    column.dataIndex
                  )
                "
              >
                <div>
                  <a-input
                    v-if="editableData[record.id]"
                    v-model:value="editableData[record.id][column.dataIndex]"
                    style="margin: -5px 0"
                  />
                  <template v-else>
                    {{ text }}
                  </template>
                </div>
              </template>
              <template v-else-if="column.dataIndex === 'operation'">
                <div class="editable-row-operations">
                  <span v-if="editableData[record.id]">
                    <a-typography-link @click="save(record.id)"
                      >保存</a-typography-link
                    >
                    <a-popconfirm
                      title="确认取消编辑?"
                      @confirm="cancel(record.id)"
                    >
                      <a>取消</a>
                    </a-popconfirm>
                  </span>
                  <span v-else>
                    <a @click="edit(record.id)">编辑</a>
                  </span>
                </div>
              </template>
            </template>
          </a-table></a-col
        >
      </section>
    </a-row>
    <h-drawer v-model:drawerVisible="drawerVisible" title="用户添加">
      <template v-slot:content>
        <a-form
          :model="formAdd"
          v-bind="layout"
          name="nest-messages"
          :validate-messages="validateMessages"
        >
          <a-form-item
            :name="['user', 'username']"
            label="用户名称"
            :rules="[{ required: true }]"
          >
            <a-input v-model:value="formAdd.user.username" />
          </a-form-item>
          <a-form-item
            :name="['user', 'email']"
            label="用户邮箱"
            :rules="[{ type: 'email' }]"
          >
            <a-input v-model:value="formAdd.user.email" />
          </a-form-item>
          <a-form-item :name="['user', 'password']" label="用户密码">
            <a-input v-model:value="formAdd.user.password" />
          </a-form-item>
          <a-form-item
            :name="['user', 'phone']"
            label="联系方式"
            :rules="[{ min: 7, max: 11, messsage: '最大不超过11位' }]"
          >
            <a-input v-model:value="formAdd.user.phone" />
          </a-form-item>
          <a-form-item :name="['user', 'status']" label="用户状态">
            <a-input v-model:value="formAdd.user.status" />
          </a-form-item>
        </a-form>
      </template>
      <template v-slot:submit>
        <a-button type="primary" @click="onSubmit(formAdd)">提交</a-button>
      </template>
    </h-drawer>
  </main>
</template>

<script setup lang="ts">
import HPageHeader from "@/components/HPageHeader.vue";
import HDrawer from "@/components/HDrawer.vue";
import { cloneDeep } from "lodash-es";
import { defineComponent, onMounted, reactive, ref, toRefs, h } from "vue";
import type { UnwrapRef } from "vue";
import { message, Spin } from "ant-design-vue";
import {
  getUserInfo,
  searchUser,
  addUser,
  delUser,
  updateUser,
} from "@/api/user";
import { selectProps } from "ant-design-vue/lib/vc-select";
const columns = [
  {
    title: "序号",
    dataIndex: "id",
    width: "100px",
    align: "center",
  },
  {
    title: "用户名",
    dataIndex: "username",
    align: "center",
  },
  {
    title: "密码",
    dataIndex: "password",
    align: "center",
  },
  {
    title: "联系方式",
    dataIndex: "phone",
    align: "center",
  },
  {
    title: "邮箱",
    dataIndex: "email",
    width: "200px",
    align: "center",
  },
  {
    title: "状态",
    dataIndex: "status",
    align: "center",
  },
  {
    title: "创建时间",
    dataIndex: "create_time",
    width: "200px",
    align: "center",
  },
  {
    title: "operation",
    dataIndex: "operation",
    width: "200px",
    align: "center",
  },
];

let delUserRow: {}[] = reactive([]);
const rowSelection = ref({
  checkStrictly: false,
  onChange: (
    selectedRowKeys: (string | number)[],
    selectedRows: DataItem[]
  ) => {
    console.log(
      `selectedRowKeys0001: ${selectedRowKeys}`,
      "selectedRows002: ",
      selectedRows
    );
    delUserRow = selectedRows;
  },
  onSelect: (record: DataItem, selected: boolean, selectedRows: DataItem[]) => {
    console.log(record, selected, selectedRows);
  },
  onSelectAll: (
    selected: boolean,
    selectedRows: DataItem[],
    changeRows: DataItem[]
  ) => {
    console.log(selected, selectedRows, changeRows);
  },
});
interface DataItem {
  key: number;
  id: number;
  username: string;
  password: string;
  phone: string;
  email: string;
  status: number;
  create_time: string;
}
interface FormState {
  username: string;
  phone: string;
}
// drawer visible
const drawerVisible = ref<boolean>(false);
// 表单数据
const formState: UnwrapRef<FormState> = reactive({
  username: "",
  phone: "",
});
// 查询
const handleSearch = (params: FormState) => {
  console.log(params);
  searchUser(params).then((res: any) => {
    // 选择时候必须有key值
    let list = res.data.data.map((it: any) => {
      console.log(it);
      it.key = it.id;
      return it;
    });
    dataSource.list = list;
  });
};
// 重置
const handleReset = () => {
  fetchUserList();
};
// 删除用户
const handleDelete = (params: any) => {
  console.log(delUserRow);
  delUser(delUserRow).then((res) => {
    if (res.data.code !== 200) {
      Spin.setDefaultIndicator({
        indicator: h("i", {
          class: "anticon anticon-loading anticon-spin ant-spin-dot",
        }),
      });
    } else {
      message.success("用户删除成功");
      console.log(res);
      fetchUserList();
    }
  });
};
// 添加
const handleAdd = (params: any) => {
  drawerVisible.value = true;
};
const data: DataItem[] = [];
// 模拟数据
for (let i = 0; i < 100; i++) {
  data.push({
    key: i,
    id: i,
    username: `Edrward ${i}`,
    password: "32",
    phone: `1774845${i}4123`,
    email: "145565@5552.com",
    status: i,
    create_time: "2125412" + i,
  });
}
// 表格分页
const pagination = reactive({
  total: 0,
  defaultPageSize: 5,
  showTotal: (total: any) => `共 ${total} 条数据`,
  showSizeChanger: true,
  pageSizeOptions: ["4", "5", "6"],
  onShowSizeChange: (current: any, pageSize: any) => (pageSize = pageSize),
});
let dataSource = reactive({ list: [] });
const editableData: UnwrapRef<Record<string, DataItem>> = reactive({});

onMounted(() => {
  fetchUserList();
});
// 获取用户列表
const fetchUserList = async () => {
  const { data } = await getUserInfo({ username: "" });
  // 选择时候必须有key值
  let list = data.data.map((it: any) => {
    // console.log(it);
    it.key = it.id;
    return it;
  });
  dataSource.list = list;
  console.log(dataSource.list, "用户信息");
};
// 添加用户
const fetchAddUser = async (params: any) => {
  const { data } = await addUser(params);
  if (data.code === 0) {
    message.warning("添加用户失败");
  } else {
    fetchUserList();
    message.success("用户添加成功");
  }
  if (data.code === null) {
    Spin.setDefaultIndicator({
      indicator: h("i", {
        class: "anticon anticon-loading anticon-spin ant-spin-dot",
      }),
    });
  } else {
  }
  console.log(data);
};
// 更新用户
const fetchUpdateUser = async (params: any) => {
  const { data } = await updateUser(params);
  console.log(data);
  if (data.code === 200) {
    console.log(data, "用户更新成功");
    message.success("用户数据更新成功");
  } else {
    message.warning("用户数据更新失败");
  }
};

// 面包屑
const routes = [
  {
    path: "user",
    breadcrumbName: "用户管理",
  },
];

const edit = (key: number) => {
  // 编辑用户列表函数
  console.log(key, "lllllllppp");
  editableData[key] = cloneDeep(
    dataSource.list.filter((item: any) => key === item.id)[0]
  );
  console.log(editableData[key], "edit");
};
const save = (key: number) => {
  Object.assign(
    dataSource.list.filter((item: any) => key === item.id)[0],
    editableData[key]
  );
  console.log(editableData[key], "edit");
  delete editableData[key].key;
  delete editableData[key].create_time;
  console.log(editableData[key]);
  fetchUpdateUser(editableData[key]);
  delete editableData[key];
};
const cancel = (key: string) => {
  delete editableData[key];
};

// 用户添加
const layout = {
  labelCol: { span: 8 },
  wrapperCol: { span: 16 },
};

const validateMessages = {
  required: "${label} 是必填项!",
  types: {
    email: "${label} 不是邮箱格式!",
    number: "${label} 不是数字!",
  },
  number: {
    range: "${label}必须位与 ${min} and ${max}",
  },
};

const formAdd = reactive({
  user: {
    username: "",
    password: undefined,
    email: "",
    phone: "",
    status: "",
  },
});
const timeConfig = {
  rules: [
    { type: "string" as const, required: true, message: "Please select time!" },
  ],
};
const onSubmit = (formAdd: any) => {
  console.log("Success:", formAdd, "drawersubmit");
  fetchAddUser(formAdd); // 添加用户
  drawerVisible.value = false;
};
</script>

<style lang="scss" scoped>
.user-main {
  width: 100%;
  height: calc(100% - 75px);
  padding: 20px;
  background: #ffffff;
  .table-body {
    width: 100%;
    .form-main {
      margin-bottom: 20px;
    }
  }
  .editable-row-operations a {
    margin-right: 8px;
  }
}
</style>